from flask import Flask, request, jsonify, render_template
from flask_sqlalchemy import SQLAlchemy
from flask_restful import Api, Resource
import hashlib
import xmltodict
import time
import json
from datetime import datetime, timezone

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False


# 微信公众号配置
WECHAT_TOKEN = "wyt0206"  # 替换为你的微信公众号Token

db = SQLAlchemy(app)
api = Api(app)

# 添加测试路由
@app.route('/')
def index():
    return "Welcome to WeChat Backend!"

@app.route('/test')
def test():
    return "Test endpoint is working!"

@app.route('/debug')
def debug():
    return {
        'headers': dict(request.headers),
        'url': request.url,
        'method': request.method,
        'args': dict(request.args)
    }

@app.route('/wechat', methods=['GET', 'POST'])
def wechat():
    print(f"Received {request.method} request to /wechat")
    print(f"Headers: {dict(request.headers)}")
    print(f"Args: {dict(request.args)}")
    print(f"Data: {request.data}")

    if request.method == 'GET':
        signature = request.args.get('signature', '')
        timestamp = request.args.get('timestamp', '')
        nonce = request.args.get('nonce', '')
        echostr = request.args.get('echostr', '')

        if not all([signature, timestamp, nonce]):
            return "Missing parameters", 400

        token = WECHAT_TOKEN
        temp_list = [token, timestamp, nonce]
        temp_list.sort()
        temp_str = ''.join(temp_list)
        hash_obj = hashlib.sha1(temp_str.encode('utf-8'))

        print(f"Token: {token}")
        print(f"Signature: {signature}")
        print(f"Calculated: {hash_obj.hexdigest()}")

        if hash_obj.hexdigest() == signature:
            return echostr
        return 'Invalid signature'

    elif request.method == 'POST':
        try:
            xml_data = request.data
            print(f"Received XML: {xml_data}")

            xml_dict = xmltodict.parse(xml_data)
            print(f"Parsed dict: {xml_dict}")

            msg_type = xml_dict['xml']['MsgType']
            from_user = xml_dict['xml']['FromUserName']
            to_user = xml_dict['xml']['ToUserName']

            if msg_type == 'text':
                content = xml_dict['xml']['Content'].strip()
                reply_content = "收到消息：" + content

                if content == '帮助':
                    reply_content = """支持的命令：
1. 搜索 关键词 - 搜索职位信息
2. 页 关键词 页码 - 查看搜索结果的其他页
3. 添加 公司名|职位名|薪资|描述 - 添加新职位
4. 更新 ID|公司名|职位名|薪资|描述 - 更新职位信息
5. 删除 ID - 删除职位信息
6. 帮助 - 显示此帮助信息"""

                reply = {
                    'xml': {
                        'ToUserName': from_user,
                        'FromUserName': to_user,
                        'CreateTime': int(time.time()),
                        'MsgType': 'text',
                        'Content': reply_content
                    }
                }

                response_xml = xmltodict.unparse(reply)
                print(f"Sending response: {response_xml}")
                return response_xml

        except Exception as e:
            print(f"Error: {str(e)}")
            return str(e), 500

    return 'OK'

if __name__ == '__main__':
    with app.app_context():
        db.create_all()
    app.run(debug=True, port=8080)